package com.wms.handler;

import com.wms.entity.WmsReturnMaterial;
import com.wms.entity.WmsReturnMaterialMx;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import java.util.List;
import java.util.Map;

/**
 * 车间退料审核
 */
public class WorkShopReturnMaterialAuditHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		boolean isOk = false;
		String msg = "保存失败!";
		try {
			OBContext.setAdminMode();
			JSONObject reqData = new JSONObject(data);
			String id = reqData.getString("recordId");
			boolean isPass = reqData.getBoolean("isPass");
			String description = reqData.getString("description");
			// 新建头信息
			WmsReturnMaterial material = OBDal.getInstance().get(WmsReturnMaterial.class, id);
			List<WmsReturnMaterialMx> hzList = material.getWmsReturnMaterialMxList();
			if (hzList == null || hzList.size() == 0) {
				throw new Exception("退料明细未维护！");
			}
			
			material.setId(id);
			material.setStatus(isPass ? "PASS" : "NO_PASS");//通过
			material.setDescription(description);
			OBDal.getInstance().save(material);
			
			isOk = true;
			msg = "保存成功!";
			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
			isOk = false;
			msg = e.getMessage();
			logger.error("车间退料申请单审核失败：", e);
		} finally {
			OBContext.restorePreviousMode();
			try {
				jsonRep.put("result", isOk);
				jsonRep.put("msg", msg);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return jsonRep;
	}
}